<template>
  <picker
    :mode="mode"
    :value="value"
    :range="range"
    :range-key="rangeKey"
    :start="start"
    :end="end"
    :fields="fields"
    :disabled="disabled"
    @change="handleChange"
    @cancel="pickerActive = false"
  >
    <view
      class="form-selector picker-c"
      :class="[{ active: !!value }]"
      @tap="pickerActive = true"
    >
      {{ content }}
      <view
        class="select-icon m-iconfont"
        :class="[{ 'picker-active': pickerActive }]"
        >&#xe65c;</view
      >
    </view>
  </picker>
</template>

<script>
export default {
  name: "m-picker",
  props: {
    placeholder: {
      type: String,
      default: "请选择",
    },
    mode: {
      type: String,
      default: "date",
    },
    fields: {
      type: String,
      default: "day",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    value: {
      type: String,
      default: "",
    },
    start: {
      type: String,
      default: "",
    },
    end: {
      type: String,
      default: "",
    },
    range: {
      type: Array,
      default: () => {
        return {};
      },
    },
    rangeKey: {
      type: String,
      default: "label",
    },
  },
  data() {
    return {
      pickerActive: false,
    };
  },
  computed: {
    content() {
      let content = "";
      switch (this.mode) {
        case "selector":
          content = this.value
            ? this.range[this.value][this.rangeKey]
            : this.placeholder;
          break;
        default:
          content = this.value || this.placeholder;
          break;
      }
      return content;
    },
  },
  methods: {
    handleChange({ detail: { value } }) {
      this.pickerActive = false;
      this.$emit("input", "" + value);
    },
  },
};
</script>

<style lang="scss" scoped>
.picker-c {
  .picker-active {
    transform: rotate(180deg);
  }
}
</style>
